<template>
  <view class="complete-profile-container">
    <!-- 蓝色区域内容 -->
    <view class="top-content">
      <view class="title">完善个人信息</view>
      <view class="subtitle">完善您的个人信息以获得更好的使用体验</view>
    </view>

    <!-- 白色区域 -->
    <view class="bottom-content">
      <!-- 头像上传 -->
      <view class="avatar-section">
        <view class="avatar-wrapper" @click="chooseAvatar">
          <image v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
          <view v-else class="avatar-placeholder">
            <wd-icon name="fill-camera" size="28" color="#999" />
          </view>
          <view class="avatar-upload">
            <wd-icon name="camera" size="16" color="#fff" />
          </view>
        </view>
        <view class="avatar-tip">点击更换头像</view>
      </view>
      <!-- 表单部分 -->
      <view class="form-section">
        <wd-form ref="formRef" :model="userForm">
          <!-- 用户名输入框 -->
          <view class="input-wrap">
            <text class="input-label">用户名</text>
            <input
              v-model="userForm.username"
              class="form-input"
              placeholder="请输入您的用户名"
              placeholder-style="color: #999; font-weight: normal;"
            />
            <wd-icon
              v-if="userForm.username"
              name="close-fill"
              size="18"
              color="#999"
              class="clear-icon"
              @click="userForm.username = ''"
            />
          </view>
          <view class="divider"></view>

          <!-- 手机号输入框 -->
          <view class="input-wrap">
            <text class="input-label">手机号</text>
            <input
              v-model="userForm.mobile"
              class="form-input"
              type="number"
              maxLength="11"
              placeholder="请输入您的手机号"
              placeholder-style="color: #999; font-weight: normal;"
            />
            <wd-icon
              v-if="userForm.mobile"
              name="close-fill"
              size="18"
              color="#999"
              class="clear-icon"
              @click="userForm.mobile = ''"
            />
          </view>
          <view class="divider"></view>

          <!-- 验证码输入框 -->
          <view class="input-wrap">
            <text class="input-label">验证码</text>
            <input
              v-model="userForm.code"
              class="form-input"
              type="number"
              placeholder="请输入验证码"
              placeholder-style="color: #999; font-weight: normal;"
            />
            <button
              class="verification-btn"
              :disabled="countdown > 0 || !validateMobile(userForm.mobile)"
              @click="handleGetVerificationCode"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : "获取验证码" }}
            </button>
            <wd-icon
              v-if="userForm.code"
              name="close-fill"
              size="18"
              color="#999"
              class="clear-icon"
              @click="userForm.code = ''"
            />
          </view>
          <view class="divider"></view>

          <!-- 行政区划选择 -->
          <view class="input-wrap" @click="showRegionPicker = true">
            <text class="input-label">所在地</text>
            <view class="region-value">
              <wdColPicker @confirm="handleConfirm"></wdColPicker>
            </view>
          </view>
          <view class="divider"></view>

          <!-- 密码输入框 -->
          <view class="input-wrap">
            <text class="input-label">密码</text>
            <input
              v-model="userForm.password"
              class="form-input"
              type="password"
              placeholder="请设置登录密码"
              placeholder-style="color: #999; font-weight: normal;"
            />
            <view class="password-toggle" @click="togglePasswordVisibility">
              <wd-icon :name="showPassword ? 'eye-close' : 'eye-open'" size="18" color="#999" />
            </view>
          </view>
          <view class="divider"></view>

          <!-- 确认密码输入框 -->
          <view class="input-wrap">
            <text class="input-label">确认密码</text>
            <input
              v-model="userForm.confirmPassword"
              class="form-input"
              type="password"
              placeholder="请再次输入密码"
              placeholder-style="color: #999; font-weight: normal;"
            />
            <view class="password-toggle" @click="toggleConfirmPasswordVisibility">
              <wd-icon
                :name="showConfirmPassword ? 'eye-close' : 'eye-open'"
                size="18"
                color="#999"
              />
            </view>
          </view>
          <view class="divider"></view>

          <!-- 提交按钮 -->
          <view class="button-wrap">
            <button
              class="submit-button"
              :disabled="submitting"
              :style="submitting ? 'opacity: 0.7;' : ''"
              @click="handleSubmit"
            >
              提交
            </button>
          </view>
        </wd-form>
      </view>
    </view>

    <!-- 弹窗 -->
    <wd-toast />

    <!-- 头像裁剪 -->
    <wd-img-cropper v-model="avatarShow" :img-src="originalSrc" @confirm="handleAvatarConfirm" />
  </view>
</template>

<script lang="ts" setup>
import { onLoad } from "@dcloudio/uni-app";
import { useToast } from "wot-design-uni";
// import { useUserStore } from "@/store/modules/user"; // 注释掉未使用的导入
import { ref } from "vue";
import AuthAPI from "@/api/auth";
import FileAPI, { type FileInfo } from "@/api/file";
import UserAPI from "@/api/system/user";
import wdColPicker from "@/components/wd-picker/index.vue";
import { getToken, setUserInfo } from "@/utils/cache";
const toast = useToast();
const formRef = ref();
// const userStore = useUserStore(); // 暂时注释掉未使用的变量
const submitting = ref(false);
const redirectPath = ref("/pages/index/index");
const token = ref("");

// 表单数据
const userForm = ref({
  username: "",
  mobile: "",
  code: "",   // 验证码
  password: "",
  confirmPassword: "",
  areaCode: "",
  avatar: "",
});

// 验证码倒计时状态
const countdown = ref(0);
const timer = ref<number | null>(null);

// 密码可见性控制
const showPassword = ref(false);
const showConfirmPassword = ref(false);

// 行政区划选择器
const showRegionPicker = ref(false);

// 行政区划数据
const regionColumns = ref([]);
const provinces = ref([]);
const cities = ref([]);
const districts = ref([]);

// 头像上传相关
const avatarShow = ref(false);
const originalSrc = ref("");

// 模拟行政区划数据
const mockRegionData = [];
// 获取参数
onLoad((options: any) => {
  // 保存跳转路径
  if (options.redirect) {
    redirectPath.value = decodeURIComponent(options.redirect);
  }
  // 从缓存中获取token
  token.value = getToken();
  // 初始化行政区划数据
  initRegionData();
});

// 初始化行政区划数据
const initRegionData = () => {
  // 模拟加载省份数据
  provinces.value = mockRegionData.map((item) => item.name);

  // 设置选择器列数据
  if (provinces.value.length > 0) {
    regionColumns.value = [provinces.value, [], []];

    // 初始化第一个省份的城市数据
    handleRegionChange([0]);
  }
};

// 处理行政区划选择变化
const handleRegionChange = (index: number[]) => {
  const provinceIndex = index[0];

  if (provinceIndex !== undefined && provinceIndex < mockRegionData.length) {
    // 加载城市数据
    cities.value = mockRegionData[provinceIndex].cities.map((city) => city.name);
    regionColumns.value[1] = cities.value;

    // 初始化第一个城市的区县数据
    if (cities.value.length > 0) {
      districts.value = mockRegionData[provinceIndex].cities[0].districts;
      regionColumns.value[2] = districts.value;
    } else {
      regionColumns.value[2] = [];
    }
  }
};

// 处理行政区划选择已在handleConfirm中实现

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 切换确认密码可见性
const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      originalSrc.value = res.tempFilePaths[0];
      avatarShow.value = true;
    },
  });
};
const handleConfirm = (e: any) => {
  if (Array.isArray(e.value) && e.value.length > 0) {
    userForm.value.areaCode = e.value[e.value.length - 1];
  }
};
// 头像裁剪完成
const handleAvatarConfirm = (event: any) => {
  const { tempFilePath } = event;
  // 显示上传中
  uni.showLoading({ title: "上传中..." });

  // 上传头像
  FileAPI.upload(tempFilePath)
    .then((fileInfo: FileInfo) => {
      userForm.value.avatar = fileInfo.url;
      uni.hideLoading();
    })
    .catch(() => {
      uni.hideLoading();
      toast.error("头像上传失败，请重试");
    });
};

// 手机号验证函数
const validateMobile = (mobile: string): boolean => {
  // 中国大陆手机号正则表达式：1开头，第二位3-9，后面9位数字
  const mobileRegex = /^1[3-9]\d{9}$/;
  return mobileRegex.test(mobile);
};

// 获取验证码
const handleGetVerificationCode = () => {
  if (!validateMobile(userForm.value.mobile)) {
    toast.warning("请输入正确的手机号");
    return;
  }

  // 设置倒计时
  countdown.value = 60;

  // 调用获取验证码接口
  UserAPI.getPhoneCode({
    mobile: userForm.value.mobile,
  })
    .then(() => {
      toast.success("验证码已发送");

      // 开始倒计时
      if (timer.value) {
        clearInterval(timer.value);
      }

      timer.value = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          if (timer.value) {
            clearInterval(timer.value);
            timer.value = null;
          }
        }
      }, 1000);
    })
    .catch((error: any) => {
      toast.error(error.message || "发送验证码失败");
      countdown.value = 0;
    });
};

// 表单验证
const validateForm = (): boolean => {
  if (!userForm.value.username.trim()) {
    toast.warning("请输入用户名");
    return false;
  }

  if (!userForm.value.mobile.trim()) {
    toast.warning("请输入手机号");
    return false;
  }

  if (!validateMobile(userForm.value.mobile)) {
    toast.warning("请输入正确的手机号");
    return false;
  }

  if (!userForm.value.code) {
    toast.warning("请输入验证码");
    return false;
  }

  // if (userForm.value.areaCode.length === 0) {
  //   toast.warning("请选择所在地");
  //   return false;
  // }

  if (!userForm.value.password) {
    toast.warning("请设置密码");
    return false;
  }

  if (userForm.value.password.length < 6) {
    toast.warning("密码长度不能少于6位");
    return false;
  }

  if (userForm.value.password !== userForm.value.confirmPassword) {
    toast.warning("两次输入的密码不一致");
    return false;
  }

  return true;
};

// 提交表单
const handleSubmit = async () => {
  if (submitting.value) return;

  if (!validateForm()) return;

  submitting.value = true;

  try {
    // 构建提交数据
    const submitData = {
      username: userForm.value.username,
      mobile: userForm.value.mobile,
      code: userForm.value.code,
      password: userForm.value.password,
      confirmPassword: userForm.value.confirmPassword,
      areaCode: userForm.value.areaCode,
      avatar: userForm.value.avatar,
    };

    // 调用API完善用户信息，将token作为第二个参数传递到请求头
    AuthAPI.WxCompleteProfile(submitData).then(() => {
      // 完善信息成功后，调用 getProfile 接口获取最新的用户信息
      UserAPI.getProfile()
        .then((res: any) => {
          if (res) {
            // 将获取到的用户信息存储到本地缓存
            setUserInfo(res);
          }
          toast.success("信息完善成功");
          // 跳转首页
          setTimeout(() => {
            uni.reLaunch({
              url: redirectPath.value,
            });
          }, 1500);
        })
        .catch((error: any) => {
          console.error("获取用户信息失败:", error);
          toast.error("获取用户信息失败，请重试");
        });
    });
  } catch (error: any) {
    console.error("信息完善失败:", error);
    toast.error(error?.message || "信息完善失败，请重试");
  } finally {
    submitting.value = false;
  }
};
// 组件卸载时清理定时器
import { onUnmounted } from "vue";
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});
</script>

<style lang="scss" scoped>
.verification-btn {
  min-width: 180rpx;
  height: 60rpx;
  padding: 0 16rpx;
  font-size: 24rpx;
  line-height: 60rpx;
  color: #007aff;
  background-color: transparent;
  border: 1px solid #007aff;
  border-radius: 30rpx;
  margin-right: 10rpx;
}

.verification-btn:disabled {
  color: #999;
  border-color: #999;
}
.complete-profile-container {
  position: relative;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.top-content {
  padding: 50rpx 40rpx;
  background-color: #007aff;
  color: #fff;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.subtitle {
  font-size: 28rpx;
  opacity: 0.9;
}

.bottom-content {
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  margin-top: -30rpx;
  padding-top: 30rpx;
  padding-bottom: 40rpx;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.avatar-section .avatar-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.avatar-section .avatar-wrapper .avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
}

.avatar-section .avatar-wrapper .avatar-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 160rpx;
  height: 160rpx;
  background-color: #f5f7fa;
  border-radius: 50%;
}

.avatar-section .avatar-wrapper .avatar-upload {
  position: absolute;
  right: 5rpx;
  bottom: 5rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40rpx;
  height: 40rpx;
  background-color: #4080ff;
  border: 2rpx solid #fff;
  border-radius: 50%;
}

.avatar-section .avatar-tip {
  font-size: 26rpx;
  color: #666;
}

.form-section {
  padding: 0 40rpx;
}

.input-wrap {
  display: flex;
  align-items: center;
  height: 96rpx;
  position: relative;
}

.input-label {
  width: 160rpx;
  font-size: 30rpx;
  color: #333;
}

.form-input {
  flex: 1;
  height: 100%;
  font-size: 30rpx;
  color: #333;
}

.clear-icon {
  margin-left: 20rpx;
}

.region-value {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 30rpx;
  color: #666;
}

.password-toggle {
  margin-left: 20rpx;
}

.divider {
  height: 1rpx;
  background-color: #f0f0f0;
  margin-left: 40rpx;
}

.button-wrap {
  margin-top: 60rpx;
  margin-bottom: 40rpx;
}

.submit-button {
  width: 100%;
  height: 96rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 48rpx;
  line-height: 96rpx;
}

.submit-button:active {
  background-color: #0062cc;
}
</style>
